import codecs
import logging.config
import os


class UTF8StreamHandler(logging.StreamHandler):
    def emit(self, record):
        try:
            msg = self.format(record)
            stream = codecs.getwriter('utf-8')(self.stream)
            stream.write(msg + self.terminator)
            self.flush()
        except RecursionError:  # See issue 36272
            raise
        except Exception:
            self.handleError(record)


# 获取当前脚本所在的目录
script_dir = os.path.dirname(os.path.abspath(__file__))

# 构建相对路径到项目根目录
project_root = os.path.dirname(script_dir)
log_file_path = os.path.join(project_root, 'app.log')  # 直接放在项目根目录下

# 日志配置字典
logging_config = {
    'version': 1,
    'formatters': {
        'verbose': {
            'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        }
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': log_file_path,
            'maxBytes': 10485760,  # 10MB
            'backupCount': 5,
            'formatter': 'verbose',
            'encoding': 'utf-8',
        },
    },
    'loggers': {
        '': {  # root logger
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

# 应用日志配置
logging.config.dictConfig(logging_config)
# 获取全局 Logger 实例
logger = logging.getLogger()
